package com.gombe.credit.app.ui.fragment

import android.content.Intent
import android.content.pm.PackageManager
import android.provider.ContactsContract
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gombe.credit.app.R
import com.gombe.credit.app.common.CommonFragment
import com.gombe.credit.app.configs.GombeCreditApiUrl.addCommonParams
import com.gombe.credit.app.configs.GombeCreditConfigs
import com.gombe.credit.app.databinding.FragmentGombeCreditStepContactBinding
import com.gombe.credit.app.event.GombeCreditEventData
import com.gombe.credit.app.event.GombeCreditEventPointType
import com.gombe.credit.app.event.room.GombeCreditPointManager
import com.gombe.credit.app.ui.activity.ActGombeCreditProcessSteps
import com.gombe.credit.app.ui.adapter.AdapterGombeCreditStepContact
import com.gombe.credit.app.utils.GombeCreditDeepCopyUtil
import com.gombe.credit.app.utils.GombeCreditDensityUtil
import com.gombe.credit.app.utils.decoration.LinearSpacingItemDecoration
import com.gombe.credit.app.utils.log.GombeCreditLogger
import org.json.JSONArray
import org.json.JSONObject
import java.util.regex.Pattern

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/19 10:38
 * @Annotation：认证流程 - 联系人
 */
class FragmentGombeCreditStepContact(): CommonFragment() {
    private var _binding: FragmentGombeCreditStepContactBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "gombe credit step contact binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var contactAdapter: AdapterGombeCreditStepContact? = null
    private var cacheCntItem = ""

    private var authStepAct: ActGombeCreditProcessSteps? = null
    private var stepItem: JSONObject? = null
    private var stepTitle = ""
    constructor(act: ActGombeCreditProcessSteps, stepItem: JSONObject): this(){
        this.authStepAct = act
        this.stepItem = stepItem
    }

    override fun takeGombeCreditRootView(inflater: LayoutInflater): View {
        _binding = FragmentGombeCreditStepContactBinding.inflate(inflater)
        return binding.root
    }

    override fun initGombeCreditView() {
        val showKey = getString(R.string.gombe_credit_process_step_contact_tips_repay_on_time)
        val showText = String.format(getString(R.string.gombe_credit_process_step_contact_tips),showKey)
        val startIndex = showText.indexOf(showKey)
        val contactTipsSpannable = SpannableString(showText)
        contactTipsSpannable.setSpan(ForegroundColorSpan(getColor(R.color.gombe_credit_FF000FCC)), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
//        contactTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startIndex1, startIndex1 + showKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
//        contactTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startIndex2, startIndex2 + showKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textContactTips?.text = contactTipsSpannable

        initGombeCreditStepCntListView()
        //联系人信息额度增加数额 = 产品额度 / 2 * 0.05
        _binding?.textCreditLimitAddAmount?.text = String.format(getString(R.string.gombe_credit_process_step_loan_amount_add),"+${stepItem?.optString("creditLimitAmount")}")

        //去掉增加联系人功能
        _binding?.btnContactAdd?.visibility = View.INVISIBLE
        //提交按钮放到外层
        _binding?.btnContactNext?.visibility = View.INVISIBLE
        _binding?.textCreditLimitAddAmount?.visibility = View.INVISIBLE
    }

    override fun initGombeCreditListener() {
        //添加
        _binding?.btnContactAdd?.setOnClickListener {
            if (cacheCntItem.isNotEmpty()){
                contactAdapter?.addLastItem(JSONObject(cacheCntItem))
                contactAdapter?.notifyDataSetChangedWrapper()
            }

            contactAdapter?.let {
                //最多添加50个联系人
                _binding?.btnContactAdd?.isEnabled = it.itemCount < 50
            }
        }

        //提交
        _binding?.btnContactNext?.setOnClickListener {
            onGombeCreditStepCntSubmitAction()
        }
    }

    override fun takeGombeCreditData() {
        //是否支持通讯录选择联系人
        val isContactPick = isGombeCreditCntPick()
        val dataList = arrayListOf<JSONObject>()
        stepItem?.let {
            stepTitle = it.optString("stepTitle")
            //联系人关系关键字
            val relationOtherKey = it.optString("relationOtherKey",getString(R.string.gombe_credit_process_step_contact_relation_other))
            val relationOtherHint = it.optString("relationOtherHint",getString(R.string.gombe_credit_process_step_contact_relation_other_hint))
            // TODO: 这里dataList需要深拷贝，否则列表会共用一个数据源
            val stringCopy = GombeCreditDeepCopyUtil(it.optString("dataList"))
            for (i in 0..< it.optInt("itemCount")){
                val obj = JSONObject()
                val dataArray = JSONArray(stringCopy.content)
                for (j in 0..<dataArray.length()){
                    val dataObj = dataArray.optJSONObject(j)
                    dataObj.put("isContactPick",isContactPick)
                    dataObj.put("title",dataObj.optString("title"))
                    when(dataObj.optString("action")){
                        "CONTACT_GROUP_RELATION",
                        "SELECT",
                        -> {
//                            dataObj.put("action", "SELECT")
                            var relationShips = it.optJSONArray("relationShips")
                            if (GombeCreditConfigs.isGombeCreditSwahili()){
                                relationShips = it.optJSONArray("relationShips_sw")
                            }
                            val valueArray = relationShips?.optJSONArray(i)
                            val values = JSONArray()
                            valueArray?.let { array ->
                                for (n in 0..< array.length()) {
                                    val value = JSONObject()
                                    value.put("title", array.optString(n))
                                    if (GombeCreditConfigs.isGombeCreditSwahili()){
                                        value.put("title_sw", array.optString(n))
                                    }
                                    value.put("value", array.optString(n))
                                    values.put(value)
                                }
                            }
                            dataObj.put("values", values)
                            dataObj.put("relationOtherKey",relationOtherKey)
                            dataObj.put("relationOtherHint",relationOtherHint)
                        }
                        "CONTACT_GROUP_PHONE" -> {//联系人电话
                            dataObj.put("action","CONTACT_GROUP_PHONE")
                        }
                        "CONTACT_GROUP_NAME" -> {//联系人姓名
                            dataObj.put("action","CONTACT_GROUP_PHONE")
                        }
                        else -> {
                            dataObj.put("action","INPUT")
                        }
                    }
                }
                obj.put("stepTitle",stepTitle)
                obj.put("dataList",dataArray)
                dataList.add(obj)
            }
        }
        contactAdapter?.data = dataList
        //缓存最后一个联系人item数据，用户新增item
        cacheCntItem = GombeCreditDeepCopyUtil(contactAdapter?.lastItem.toString()).content

        //联系人启动埋点，防止多次上报
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.STEP_CONTACT_START)
    }

    /**
     * 初始化Views
     */
    private fun initGombeCreditStepCntListView(){
        //        _binding?.recyclerViewContact.setHasFixedSize(true)
        _binding?.recyclerViewContact?.isNestedScrollingEnabled = false
        _binding?.recyclerViewContact?.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        _binding?.recyclerViewContact?.layoutManager = layoutManager
        val topDecoration = GombeCreditDensityUtil.dp2px(16f)
        _binding?.recyclerViewContact?.addItemDecoration(LinearSpacingItemDecoration(0,0,topDecoration,0))
        contactAdapter = AdapterGombeCreditStepContact(_binding?.root,_binding?.recyclerViewContact)
        _binding?.recyclerViewContact?.adapter = contactAdapter
        _binding?.recyclerViewContact?.itemAnimator = DefaultItemAnimator()
        contactAdapter?.setOnChildItemSelectMobileListener(object : AdapterGombeCreditStepContact.IChildItemSelectMobileListener{
            override fun onChildSelectMobileClick(parentPosition: Int, childModel: JSONObject) {
                val startTime = System.currentTimeMillis()
                authStepAct?.pickContact?.startPickContact { contactName, contactMobile ->
                    GombeCreditLogger.e(">>>>>>>>>>>>>>>>>>>>>$contactName>>>>>>>$contactMobile")
                    val subTimestamp = System.currentTimeMillis() - startTime

                    contactAdapter?.let {
                        val parentItem = it.getItem(parentPosition)

                        //设置联系人名称
                        val dataArray = parentItem.optJSONArray("dataList")
                        if (dataArray != null) {
                            for (i in 0..<dataArray.length()) {
                                val itemObj = dataArray.optJSONObject(i)
                                if (itemObj.optString("paramName") == "fullName"){
                                    val obj = JSONObject()
                                    obj.put("title",contactName)
                                    obj.put("value",contactName)
                                    itemObj.put("selectItem",obj)
                                    val subRemark = "${contactName}$$${subTimestamp}"
                                    addEventPointRequestAction(String.format(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.STEP_XX_SELECT, "${parentItem.optString("stepTitle")}_${itemObj.optString("paramName")}_${parentPosition+1}"), subRemark)
                                    continue
                                }
                                if (itemObj.optString("paramName") == "mobile"){
                                    val obj = JSONObject()
                                    obj.put("title",contactMobile)
                                    obj.put("value",contactMobile)
                                    itemObj.put("selectItem",obj)
                                    val subRemark = "${contactMobile}$$${subTimestamp}"
                                    addEventPointRequestAction(String.format(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.STEP_XX_SELECT, "${parentItem.optString("stepTitle")}_${itemObj.optString("paramName")}_${parentPosition+1}"), subRemark)
                                    continue
                                }
                            }
                        }
                        it.notifyItemChanged(parentPosition)
                    }
                }
            }
        })
    }

    /**
     * 联系人提交
     */
    private fun onGombeCreditStepCntSubmitAction(){
        _binding?.root?.clearFocus()
        if (!isAllowContactSubmit() || stepItem == null){
            showErrorTipsDialog(getString(R.string.gombe_credit_dialog_tips_submit_error), stepTitle)
            return
        }
        val params = JSONObject().addCommonParams()
        stepItem?.let {
            params.put("path",it.optString("apiUrl").replace("/",""))
        }
        //拼接上传数据格式
        val paramArray = JSONArray()
        contactAdapter?.let { adapter ->
            for (i in 0..< adapter.itemCount){
                val obj = JSONObject()
                val dataArray = adapter.getItem(i).optJSONArray("dataList")
                dataArray?.let {
                    for (j in 0..< it.length()){
                        val item = it.optJSONObject(j)
                        val paramName = item.optString("paramName")
                        val selectItem = item.optJSONObject("selectItem")
                        var paramValue = selectItem?.optString("value")
                        if (paramName == "relation" && paramValue == item.optString("relationOtherKey")){
                            paramValue = selectItem?.optString("otherValue")
                            //如果关系为“Other”，输入的内容为纯数字，则直接传“Other”
                            if (isGombeCreditAllNumber(paramValue)){
                                paramValue = item.optString("relationOtherKey")
                            }
                        }
                        obj.put(paramName,paramValue)
                    }
                }
                paramArray.put(obj)
            }
        }
        stepItem?.let {
            params.put(it.optString("contactParamName"),paramArray)
        }
        addEventPointRequestAction(String.format(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.STEP_XX_NEXT, stepTitle),"")
        // TODO: 进件信息点下一步 需上报所有埋点
        GombeCreditPointManager.getInstance().manualReport()

        authStepAct?.onGombeCreditProcessStepSubmitAction(params)
    }

    /**
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowContactSubmit(): Boolean{
        val dataList = arrayListOf<JSONObject>()
        contactAdapter?.let {
            for (i in 0..< it.itemCount){
                val dataArray = it.getItem(i).optJSONArray("dataList")
                dataArray?.let { array ->
                    for (j in 0..< array.length()){
                        val item = array.optJSONObject(j)
                        dataList.add(item)
                    }
                }
            }
        }
        //是否允许提交
        var isAllow = true
        for (i in 0..<dataList.size){
            val item = dataList[i]
            //存在 isMust && isMust == ”NO“  非必填
            if (item.has("isMust") && item.optString("isMust") == "NO"){
                continue
            }
            //必填 && 没有内容 || 内容为空
            if (!item.has("selectItem")){
                isAllow = false
                break
            }
            val selectItem = item.optJSONObject("selectItem")
            if (selectItem == null){
                isAllow = false
                break
            }
            val paramName = item.optString("paramName")
            val paramValue = selectItem.optString("value")
            if (paramValue.isEmpty()){
                isAllow = false
                break
            }
            if (paramName == "relation" && paramValue == item.optString("relationOtherKey") && selectItem.optString("otherValue","").isEmpty()){
                isAllow = false
                break
            }
        }
        return isAllow
    }

    /**
     * 是否支持通讯录选择
     */
    private fun isGombeCreditCntPick(): Boolean{
        val intentContact = Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI)
        val resolveInfoCType = getAct().packageManager.resolveActivity(intentContact, PackageManager.MATCH_DEFAULT_ONLY)
        return resolveInfoCType != null
    }

    /**
     * 是否全为数字
     */
    private fun isGombeCreditAllNumber(text: String?): Boolean {
        if (text.isNullOrEmpty()){
            return false
        }
        val formatLct = "^-?\\d+\\.?\\d*$"
        val patternLct = Pattern.compile(formatLct)
        return patternLct.matcher(text.trim()).matches()
    }

    override fun onGombeCreditPublishEvent(event: GombeCreditEventData) {
        super.onGombeCreditPublishEvent(event)
        when(event.eventType){
            GombeCreditEventData.TYPE.GOMBECREDIT_PROCESS_STEP_SUBMIT -> {
                onGombeCreditStepCntSubmitAction()
            }
            else -> {

            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.STEP_CONTACT_END)
    }
}